<template>
  <div class="login-container container">
    <div class="login-form card mx-auto">
      <div class="card-body">
        <h2 class="card-title text-center mb-4">用户登录</h2>
        <form @submit.prevent="login">
          <div class="mb-3">
            <label for="username" class="form-label">用户名:</label>
            <input type="text" id="username" v-model="username" class="form-control" required>
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">密码:</label>
            <input type="password" id="password" v-model="password" class="form-control" required>
          </div>
          <div class="mb-3">
            <label for="role" class="form-label">角色:</label>
            <select id="role" v-model="role" class="form-select" required>
              <option value="student">学生</option>
              <option value="teacher">教师</option>
              <option value="principal">校长</option>
            </select>
          </div>
          <div class="d-grid">
            <button type="submit" class="btn btn-primary">登录</button>
          </div>
          <p class="register-link text-center mt-3">
            还没有账户？<router-link to="/register">立即注册</router-link>
          </p>
        </form>
        <div v-if="errorMessage" class="alert alert-danger mt-3" role="alert">
          {{ errorMessage }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Login',
  data() {
    return {
      username: '',
      password: '',
      role: 'student',
      errorMessage: ''
    }
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('/api/users/login', {
          username: this.username,
          password: this.password,
          role: this.role
        })
        
        if (response.data) {
          // 保存用户信息到本地存储
          localStorage.setItem('user', JSON.stringify(response.data))
          localStorage.setItem('token', 'fake-jwt-token') // 模拟token
          
          // 跳转到首页
          this.$router.push('/')
        }
      } catch (error) {
        console.error('登录错误:', error)
        if (error.response) {
          this.errorMessage = `登录失败：${error.response.data || '用户名或密码错误'}`
        } else {
          this.errorMessage = '网络错误，请检查服务器是否正常运行'
        }
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.login-form {
  width: 100%;
  max-width: 400px;
}
</style>